package com.peanut.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.mvc.annotation.RequestMapping;
import com.mvc.annotation.ResponseBody;
import com.peanut.constants.Status;
import com.peanut.entity.JsonResult;
import com.spring.annotation.Controller;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;

/**
 * 全局的图片上传controller
 */

@Controller
@Slf4j
public class ImageUploadController {

	static {
		// File dir = new File("/uploadFile");   // bug 修复， 这里/uploadFile 在win下没有异常，但在 linux 下表示在根目录下创建 uploadFile 导致后面相对路径找不到上传路径
		File dir = new File("uploadFile");   // bug 修复， 这里/uploadFile 在win下没有异常，但在 linux 下表示在根目录下创建 uploadFile 导致后面相对路径找不到上传路径
		if (!dir.exists()) {
			if(!dir.mkdir()){
				log.error("上传文件夹创建失败!");  // 不抛异常了, 及时创建文件夹就可以
			}
		}
	}
	

	@ResponseBody
	@RequestMapping(value = "/upload/imageUpload.do")
	public JsonResult receiveImage(HttpServletRequest request) throws ServletException, IOException {
		File dir = new File("/uploadFile");
		
		Collection<Part> parts = request.getParts();
		
		if (parts.size() != 1) {
			return JsonResult.status(Status.UPLOAD_FILE_LIMIT);
		}
		
		Part part = (Part) parts.toArray()[0];
		
		String fileName = part.getSubmittedFileName();                           // 提交的文件名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));  //拿到后缀
		
		InputStream inputStream = part.getInputStream();
		String md5FileName = DigestUtil.md5Hex(inputStream);
		
		String fullFilePath = request.getServletContext().getRealPath("/uploadFile/") + md5FileName + suffixName;
		File file = new File(fullFilePath);
		
		if (file.exists()) {
			JsonResult r = JsonResult.success();
			r.setData(request.getContextPath() + "/uploadFile/" + md5FileName + suffixName);
			return r;
		}
		
		part.write(fullFilePath);
		
		JsonResult r = JsonResult.status(Status.UPLOAD_SUCCESS);
		r.setData(request.getContextPath() + "/uploadFile/" + md5FileName + suffixName);
		return r;
	}
}
